﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Xml;
using System.Reflection;
using Wangzeran.CodeMaker.Core.Model;
using Wangzeran.CodeMaker.Core.Template;

namespace Wangzeran.CodeMaker.Core.Config
{
    /// <summary>
    /// 模板文件处理
    /// </summary>
    public class TemplatesSectionHandler : IConfigurationSectionHandler
    {

        private const string TEMPLATE_NODE = "template";

        private const string ATTR_FILEPATH = "file";


        #region IConfigurationSectionHandler 成员

        public object Create(object parent, object configContext, XmlNode section)
        {
            string absolutelyPath = Assembly.GetExecutingAssembly().Location;
            absolutelyPath = absolutelyPath.Remove(absolutelyPath.LastIndexOf(@"\") + 1);

            foreach (XmlNode node in section)
            {
                try
                {
                    if (node.Name == TEMPLATE_NODE)
                    {
                        if (node.Attributes[ATTR_FILEPATH] == null)
                        {
                            continue;
                        }
                        // 获取模板的路径
                        string path = node.Attributes[ATTR_FILEPATH].Value;
                        TemplateFileModal file = new TemplateFileModal(path, absolutelyPath + path);
                        if (file.IsOk)
                        {
                            TemplateFiles.RegisterTemplateFile(file);
                        }
                    }
                }
                catch (Exception)
                {
                    continue;
                }
            }

            return null;
        }

        #endregion
    }
}
